<?php

namespace App\Http\Controllers\User;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Repos\ConsultRepo;
use App\Repos\UserExpertRepo;
use App\Models\User;
use App\Models\WxuserInfo;
use App\Services\Wechat;

class ConsultController extends Controller
{
    public function index(Request $request)
    {   
        $where  = [];
        $wxuser =  session('wechat.oauth_user.default'); //
        
        
        $where['openid'] = $wxuser->id;
        if($request->keyword) {
            $where['keyword'] = trim($request->keyword);
        }
        
        $list = ConsultRepo::pages($where,10);
        
        return view('zhuanjia.consult-list',compact('list','where'));
    }

    /**
     * 添加咨询
     */
    public function create(Request $request,$expert_id)
    {
        $wxuser =  session('wechat.oauth_user.default'); // 公众号
        $wxuser_info = '';
        $wxuser_info = WxuserInfo::where(['openid'=>$wxuser->id])->first();
        $where['id'] = (int)$expert_id;        
        $expert = UserExpertRepo::find($where);	
        return view('zhuanjia.consult-add',compact('expert','wxuser_info'));
    }

    public function store(Request $request)
    {
        $data = $request->except(['_token']);
        $wxuser =  session('wechat.oauth_user.default'); // 公众号
        // 根据 expert_id 获取专家的openid
        $expert = UserExpertRepo::find(['id'=>$request->expert_id]);
        $data['wxuser_openid'] = $wxuser->id;
        $data['expert_openid'] = object_get($expert,'user.openid');
        $data['status'] = 0;
        $data['pics'] = rtrim($data['pics'],',');
        $data['code'] = date('ymdHis').str_random(3);
        $flag = ConsultRepo::store($data);
       
        return redirect('user/consult-list');
    }

    public function show($id)
    {
        $data = ConsultRepo::find(['id'=>$id]);
        $openid =  session('wechat.oauth_user.default')->id; //
        
        $wxuser = Wechat::getUserInfo($data->wxuser_openid);
        $type = 2;
        if($openid == $data->expert_openid) {
            $type = 1;
        }
        return view('zhuanjia.consult-show',compact('data','type','wxuser'));
    }

    public function reply(Request $request)
    {
        
    }

    private function isExpert($openid)
    {
       
        $userWhere['role_id'] = 1;
        $userWhere['openid']  = $openid;        
        return User::where($userWhere)->first();
    }

  
    
}
